package org.jflame.auth.web;

import org.jflame.auth.LoginUser;
import org.jflame.auth.context.UserContextHolder;
import org.jflame.commons.config.ConfigKey;
import org.jflame.commons.config.ServletParamConfig;
import org.jflame.commons.json.JsonHelper;
import org.jflame.commons.model.CallResult;
import org.jflame.commons.model.CallResult.ResultEnum;
import org.jflame.commons.util.StringHelper;
import org.jflame.web.RedirectStrategy;

import java.io.IOException;
import java.util.Optional;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 通用登录注销servlet
 * 
 * @author charles.zhang
 */
@SuppressWarnings("serial")
public class LogoutServlet extends HttpServlet {

    private final ConfigKey<String> LOGOUT_PAGE_KEY = new ConfigKey<>("logoutPage");// 注销后跳转页面
    private final ConfigKey<String> LOGOUT_JSON_KEY = new ConfigKey<>("logoutJson");// 注销后返回的json消息,ajax请求时使用
    private String logoutPage;
    private String logoutJson;
    private LogoutHandler handlers = new CompositeLogoutHandler(new DefaultLogoutHandler());
    private RedirectStrategy redirectStrategy;

    @Override
    public void init(ServletConfig config) throws ServletException {
        ServletParamConfig servletParam = new ServletParamConfig(config);
        logoutPage = servletParam.getString(LOGOUT_PAGE_KEY);
        logoutJson = servletParam.getString(LOGOUT_JSON_KEY);
        if (StringHelper.isEmpty(logoutJson)) {
            logoutJson = JsonHelper.toJson(new CallResult<>(ResultEnum.SUCCESS.getStatus(), "登出成功"));
        }
        redirectStrategy = new RedirectStrategy(logoutPage, logoutJson);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession(false);
        if (session != null) {
            Optional<LoginUser> userOpl = UserContextHolder.getLoginUser();
            if (userOpl.isPresent()) {
                handlers.logout(request, response, userOpl.get());
            }
        }
        redirectStrategy.redirect(request, response);
    }

    public String getLogoutPage() {
        return logoutPage;
    }

    public void setLogoutPage(String logoutPage) {
        this.logoutPage = logoutPage;
    }

    public String getLogoutJson() {
        return logoutJson;
    }

    public void setLogoutJson(String logoutJson) {
        this.logoutJson = logoutJson;
    }

}
